package com.scau.bookstore.service.impl;

import com.scau.bookstore.contract.service.ItemService;
import com.scau.bookstore.common.pojo.OrderItem;
import com.scau.bookstore.repository.mapper.OrderItemDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ItemServiceImpl implements ItemService {

	@Autowired
	private OrderItemDao orderItemDao;

	/**
	 * 查询全部列表
	 * @return
	 */
	public List<OrderItem> findAll() {
		return orderItemDao.findAll();
	}

	
	/**
	 * 条件查询+分页
	 * @param whereMap
	 * @param page
	 * @param size
	 * @return
	 */
	public Page<OrderItem> findSearch(Map whereMap, int page, int size) {
		Specification<OrderItem> specification = createSpecification(whereMap);
		PageRequest pageRequest =  PageRequest.of(page-1, size);
		return orderItemDao.findAll(specification, pageRequest);
	}

	
	/**
	 * 条件查询
	 * @param whereMap
	 * @return
	 */
	public List<OrderItem> findSearch(Map whereMap) {
		Specification<OrderItem> specification = createSpecification(whereMap);
		return orderItemDao.findAll(specification);
	}

	/**
	 * 根据ID查询实体
	 * @param id
	 * @return
	 */
	public OrderItem findById(Long id) {
		return orderItemDao.findById(id).get();
	}

	/**
	 * 增加
	 * @param orderItem
	 */
	public void add(OrderItem orderItem) {
		orderItemDao.save(orderItem);
	}

	/**
	 * 修改
	 * @param orderItem
	 */
	public void update(OrderItem orderItem) {
		orderItemDao.save(orderItem);
	}

	/**
	 * 删除
	 * @param id
	 */
	public void deleteById(Long id) {
		orderItemDao.deleteById(id);
	}

	/**
	 * 动态条件构建
	 * @param searchMap
	 * @return
	 */
	private Specification<OrderItem> createSpecification(Map searchMap) {

		return (Specification<OrderItem>) (root, query, cb) -> {
			List<Predicate> predicateList = new ArrayList<>();

			return cb.and( predicateList.toArray(new Predicate[predicateList.size()]));

		};

	}

}
